﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.DAL.DocumentCenter;
using MS.InformationManagement.Support.Constants;
using MS.InformationManagement.Support;
using MS.InformationManagement.Core.Support;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;
using support = MS.InformationManagement.DAL.Support;
using System.Data;
using MS.InformationManagement.Core.Documentset;
using MS.InformationManagement.DAL.DocumentCenter;
using Office = Microsoft.Office.DocumentManagement.DocumentSets;
using MS.InformationManagement.DAL.RecordCenter;
using Microsoft.SharePoint.Utilities;

namespace MS.InformationManagement.BLL.SearchRadicado
{
    public class SearchRadicado : BaseDocumentSet<Radicado>
    {

        public IEnumerable<Radicado> SearchRadicados(string radicado, string nit, string cedula, string source, string fechaInicio, string fechaFin, int pageIndex, int pageSize, out int totalRecords)
        { 
            List<string> fields = new List<string>();
            List<string> values = new List<string>();
            List<string> types = new List<string>();
            List<string> operatorTypes = new List<string>();
            int startingPosition = pageIndex * pageSize; 

            if (!string.IsNullOrEmpty(radicado))
            {
                fields.Add(CustomSiteColumns.FIELD_DOCSET_ID_RADICADO);
                values.Add(radicado);
                types.Add("Text");
                operatorTypes.Add("Contains");
            }

            if (!string.IsNullOrEmpty(nit))
            {
                fields.Add(CustomSiteColumns.FIELD_DOCUMENT_NIT);
                values.Add(nit);
                types.Add("Text");
                operatorTypes.Add("Contains");
            }

            if (!string.IsNullOrEmpty(cedula))
            {
                fields.Add(CustomSiteColumns.FIELD_DOCUMENT_CEDULA);
                values.Add(cedula);
                types.Add("Text");
                operatorTypes.Add("Contains");
            }

            if (!string.IsNullOrEmpty(fechaInicio))
            {
                fields.Add(CustomSiteColumns.FIELD_SP_CREATED);
                string fecha = Convert.ToDateTime(fechaInicio).ToString("yyyy-MM-ddThh:mm:ssZ");
                values.Add(fecha);
                types.Add("DateTime");
                operatorTypes.Add("Geq");
            }

            if (!string.IsNullOrEmpty(fechaFin))
            {
                fields.Add(CustomSiteColumns.FIELD_SP_CREATED);
                string fecha = Convert.ToDateTime(fechaFin).ToString("yyyy-MM-ddThh:mm:ssZ");
                values.Add(fecha);
                types.Add("DateTime");
                operatorTypes.Add("Leq");
            }

            fields.Add("ContentType");
            values.Add(GlobalConstants.CTTN_INFORMATION);
            types.Add("Text");
            operatorTypes.Add("Neq");

            fields.Add("ContentType");
            values.Add(GlobalConstants.CTTN_ARCHIVE);
            types.Add("Text");
            operatorTypes.Add("Neq");

            string _cadena = string.Empty;
            string camlQuery = CamlHelper.CreateCAMLQuery(values.ToArray(), fields.ToArray(), types.ToArray(), operatorTypes.ToArray(), ref _cadena);
            List<string> viewFields = new List<string>() { CustomSiteColumns.FIELD_DOCSET_ID_RADICADO, CustomSiteColumns.FIELD_DOCUMENT_DOCUMENTAL_TYPE, CustomSiteColumns.FIELD_DOCSET_SENDERRECEPT, "Created", CustomSiteColumns.FIELD_EXPEDIENTE_ID, CustomSiteColumns.FIELD_DOCSET_KIND, CustomSiteColumns.FIELD_DOCSET_ASUNTO, CustomSiteColumns.FIELD_DOCUMENT_NIT, CustomSiteColumns.FIELD_DOCUMENT_CEDULA, CustomSiteColumns.FIELD_SP_ID };
            SPSiteDataQuery query = support.QuerySiteHelper.getSiteQueryObject(GlobalConstants.GLOBAL_USER_LIBRARY_TEMPLATE, viewFields, camlQuery);
            DataTable foundedItems = SPContext.Current.Web.GetSiteData(query);

            var foundedRadicados = (from item in foundedItems.Rows.OfType<DataRow>()
                                    select new Radicado
                                    {
                                        NoRadicado = item[CustomSiteColumns.FIELD_DOCSET_ID_RADICADO].ToString(),
                                        TipoDocumento = item[CustomSiteColumns.FIELD_DOCUMENT_DOCUMENTAL_TYPE] == null ? string.Empty : item[CustomSiteColumns.FIELD_DOCUMENT_DOCUMENTAL_TYPE].ToString(),
                                        RemitenteDestinatario = item[CustomSiteColumns.FIELD_DOCSET_SENDERRECEPT] == null ? string.Empty : item[CustomSiteColumns.FIELD_DOCSET_SENDERRECEPT].ToString(),
                                        Created = DateTime.Parse(item["Created"].ToString()),
                                        NúmeroExpediente = item[CustomSiteColumns.FIELD_EXPEDIENTE_ID] == null ? string.Empty : item[CustomSiteColumns.FIELD_EXPEDIENTE_ID].ToString(),
                                        Titulo = item[CustomSiteColumns.FIELD_DOCSET_KIND] == null ? null : new SPFieldLookupValue(item[CustomSiteColumns.FIELD_DOCSET_KIND].ToString()).LookupValue,
                                        Asunto = item[CustomSiteColumns.FIELD_DOCSET_ASUNTO] == null ? string.Empty : item[CustomSiteColumns.FIELD_DOCSET_ASUNTO].ToString(),
                                        UsuarioAsignado = item[CustomSiteColumns.FIELD_DOCUMENT_CEDULA] != null && !item[CustomSiteColumns.FIELD_DOCUMENT_CEDULA].ToString().Equals(string.Empty) ? item[CustomSiteColumns.FIELD_DOCUMENT_CEDULA].ToString() : (item[CustomSiteColumns.FIELD_DOCUMENT_NIT] == null ? string.Empty : item[CustomSiteColumns.FIELD_DOCUMENT_NIT].ToString()),
                                        ListId = new Guid(item["ListId"].ToString()),
                                        Id = int.Parse(item[CustomSiteColumns.FIELD_SP_ID].ToString())
                                    });
            List<Radicado> lstFinal = new List<Radicado>();

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite currentSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb currentWeb = currentSite.OpenWeb())
                    {
                        foreach (Radicado item in foundedRadicados)
                        {
                            SPList listCurrent = currentWeb.Lists[item.ListId];
                            CurrentLibrary = listCurrent.Title;
                            Office.DocumentSet currentDoc = GetDocumentSet((int)item.Id, currentWeb);

                            if (currentDoc.Folder != null)
                            {
                                item.AttachedFiles = (from file in currentDoc.Folder.Files.OfType<SPFile>()
                                                      where file.Item.ContentType.Name != GlobalConstants.CTTN_COPIAS_RADICADO
                                                      select new FileEntity
                                                      {
                                                          CreationDate = SPUtility.ParseDate(currentWeb, file.Item[SPBuiltInFieldId.Created].ToString(), SPDateFormat.DateTime, false),
                                                          FileContent = file.OpenBinary(),
                                                          FileName = file.Name,
                                                          FileSize = file.OpenBinary().Length / 1024,
                                                          IsMainDocument = ListHelper.ConvertToBoolean(file.Item[CustomSiteColumns.FIELD_DOCUMENT_IS_MAIN] + "")
                                                      }).ToList();
                            }
                            lstFinal.Add(item);
                        }
                    }
                }
            });

            totalRecords = lstFinal.Count();
            return lstFinal.Skip(startingPosition).Take(pageSize);
        }

        public void ValidateItems(List<string> contentTypes, string selectedItem)
        {
            string camlQuery = support.CamlHelper.GetInClausule(CustomSiteColumns.FIELD_DOCSET_ID_RADICADO, contentTypes);
            camlQuery = string.Format("<Where><And>{0}<Eq><FieldRef Name='{1}' /><Value Type='Text'>{2}</Value></Eq></And></Where>", camlQuery, CustomSiteColumns.FIELD_DOCSET_ID_RADICADO, selectedItem);
            List<string> viewFields = new List<string>() { "ID" };
            SPSiteDataQuery query = support.QuerySiteHelper.getSiteQueryObject(GlobalConstants.GLOBAL_USER_LIBRARY_TEMPLATE, viewFields, camlQuery);
            DataTable foundedItems = SPContext.Current.Web.GetSiteData(query);
            if (foundedItems.Rows.Count > 0)
                throw new Exception("No es posible agregar un radicado de entrada como respuesta del radicado seleccionado");

        }

        public void TRDValidation(string radicado)
        {
            List<string> contentTypes = new List<string>() { GlobalConstants.CTTN_RADICADO_EMPRESA, GlobalConstants.CTTN_RADICADO_EMPRESA_SALIDA, GlobalConstants.CTTN_RADICADO_INTERNO, GlobalConstants.CTTN_RADICADO_PERSONA, GlobalConstants.CTTN_RADICADO_PERSONA_SALIDA };
            string camlQueryIn = support.CamlHelper.GetInClausule(CustomSiteColumns.FIELD_DOCSET_ID_RADICADO, contentTypes);
            string camlQuery = string.Format(@"<Where><And><IsNull><FieldRef Name='{0}' /></IsNull><And><Eq><FieldRef Name='{1}' /><Value Type='Text'>{2}</Value></Eq>{3}</And></And></Where>", CustomSiteColumns.FIELD_DOCUMENT_DOCUMENTAL_TYPE, CustomSiteColumns.FIELD_DOCUMENT_RADICADO, radicado, camlQueryIn);
            List<string> viewFields = new List<string>() { "ID", CustomSiteColumns.FIELD_DOCUMENT_DCOUMENTAL_TYPE_ID, CustomSiteColumns.FIELD_DOCUMENT_DOCUMENTAL_TYPE, CustomSiteColumns.FIELD_DOCUMENT_RADICADO };
            SPSiteDataQuery query = support.QuerySiteHelper.getSiteQueryObject(GlobalConstants.GLOBAL_USER_LIBRARY_TEMPLATE, viewFields, camlQuery);
            DataTable foundedItems = SPContext.Current.Web.GetSiteData(query);
            if(foundedItems.Rows.Count == 1)
                throw new Exception("El radicado seleccionado no esta tipificado, debe tipificar el radicado antes de efectuar esta acción");

        }

        public override Core.TransactionsResponse.ITransactionResponse NewRadicado()
        {
            throw new NotImplementedException();
        }

        public override void UpdateRadicado()
        {
            throw new NotImplementedException();
        }

        public override string GetTargetLibrary(string target)
        {
            using (var dc = new DataContext(SPContext.Current.Web.Url))
            {
                var encharged = (from dept in dc.Secciones
                                 where dept.Id.ToString() == target
                                 select dept).FirstOrDefault();
                if (encharged == null)
                    throw new Exception(ExceptionConstants.ERROR_DEPARTMENT_NO_ENCHARGED);
                return PeopleHelper.GetUserById(encharged.UsuarioEncargadoCorrespondenciaId.Value).LoginName.GetUserWithOutDomain();
            }
        }

        public override void updateMetadata()
        {
            throw new NotImplementedException();
        }
    }
}
